<template> 
  <el-card class="form-container" shadow="never">
    <el-form :model="admin" :rules="loginRules" ref="adminFrom" label-width="150px">
      <el-form-item label="用户昵称：" prop="nickName">
        <el-input v-model="admin.nickName"></el-input>
      </el-form-item>
      <el-form-item label="用户名：" prop="username">
        <el-input :readonly="readonly_username" v-model="admin.username"></el-input>
      </el-form-item>

      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="admin.email"></el-input>
      </el-form-item>
      <el-form-item label="图像：" prop="icon">
        <single-upload v-model="admin.icon"></single-upload>
      </el-form-item>
     
       <el-form-item label="类型：" prop="supplyId">
        <el-radio-group v-model="admin.supplyId">
            <el-radio :label="0">商户</el-radio>
            <el-radio :label="1">店长</el-radio>
            <el-radio :label="2">店员</el-radio>
        </el-radio-group>
      </el-form-item> 

      <el-form-item label="门店：" prop="storeId">
          <el-select @change="storeChange" v-model="admin.storeId" placeholder="请选择">
            <el-option
            v-for="item in stores"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
        </el-select>
      </el-form-item> 

      <el-form-item label="班次：" prop="shiftId">
          <el-select @change="shiftChange" v-model="admin.shiftId" placeholder="请选择">
            <el-option
            v-for="item in shifts"
            :key="item.id"
            :label="item.shiftName"
            :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>


 

      <el-form-item label="角色："  prop="roleIds">
         <el-radio-group v-model="roleIds">
            <el-radio  v-for="(item,index) in allRoles" :key="index"  :label="item.id">{{item.name}}</el-radio>
        </el-radio-group>
        <!--
           <el-checkbox-group v-model="allRoles1">
          <el-checkbox v-for="(item,index) in allRoles" :key="index"   :checked="item.checked" :label="item.id">{{item.name}}</el-checkbox>
        </el-checkbox-group>
         -->
      </el-form-item>


      
      <el-form-item label="备注：">
        <el-input
          placeholder="请输入内容"
          type="textarea"
          v-model="admin.note"
          :autosize="true"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('adminFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('adminFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
  import {createAdmin, getAdmin, updateAdmin,userRoles,userRoleCheck} from '@/api/admin'
  import {fetchList as getStoreList} from '@/api/mer/shopStore'
  import {fetchList as getShiftList} from '@/api/mer/shopShift'
  import {isvalidUsername} from '@/utils/validate';
  import {fetchList} from '@/api/role'
  import SingleUpload from '@/components/Upload/singleUpload'
  const defaultAdmin={
    username: '',
    roleIds:'',
    supplyId:0
  };
  export default {
    name: 'AdminDetail',
    components:{SingleUpload},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      },
      isUser:{
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!isvalidUsername(value)) {
          callback(new Error('请输入正确的用户名'))
        } else {
          callback()
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value.length < 3) {
          callback(new Error('密码不能小于3位'))
        } else {
          callback()
        }
      };
      return {
        readonly_username:false,
        admin:Object.assign({}, defaultAdmin),
        allRoles:null,
        shifts:[],
        stores:[],
        userRoles:null,
        roleIds:null,
        listQuery: {
          pageNum: 1,
          pageSize: 100
        },
        loginRules: {
          username: [{required: true, trigger: 'blur', message: '请输入用户名',}]
        }

        }

    },
    created() {
      if (this.isEdit) {
        if(this.isUser){
          this.listQuery.adminId=-1;
          this.readonly_username = true;
        }else{
           this.listQuery.adminId=this.$route.query.id;
        }
        userRoleCheck(this.listQuery).then(res => {
          if(res.code==200){
          this.allRoles =  res.data
           for(let item of this.allRoles){
            if(item.checked){
              this.roleIds = item.id
            }
          }
        }
      });

      getAdmin(this.listQuery.adminId).then(response => {
          this.admin = response.data;
      });
      }else{
        fetchList(this.listQuery).then(response => {
          this.allRoles = response.data.records;
      });
        this.admin = Object.assign({},defaultAdmin);
      };
      this.getStores()
      this.getShifts()


    },
    computed: {
      //选中的服务保证
         /*
      allRoles1: {
     
         get() {
          let list = [];
          if (this.roleIds === undefined || this.roleIds == null || this.roleIds === '') return list;
          let ids = this.roleIds.split(',');
          for (let i = 0; i < ids.length; i++) {
            list.push(Number(ids[i]));
          }
          return list[0];
        },
       
        set(newValue) {
          let serviceIds = '';
          newValue = [newValue] 
          if (newValue != null && newValue.length > 0) {
            for (let i = 0; i < newValue.length; i++) {
              serviceIds += newValue[i] + ',';
            }
            if (serviceIds.endsWith(',')) {
              serviceIds = serviceIds.substr(0, serviceIds.length - 1)
            }
            this.roleIds = serviceIds;
          } else {
            this.roleIds = null;
          }
          
        }
    
      }
          */
    },
    methods: {
      getStores(){
        getStoreList({pageNum: 1, pageSize: 100}).then(response => {
                this.stores = response.data.records;
        })
      },
      getShifts(){
        getShiftList({pageNum: 1, pageSize: 100}).then(response => {
                this.shifts = response.data.records;
        })
      },
      shiftChange(s){
        for(let item of this.shifts){
          if(item.id==s){
            this.admin.shiftName = item.shiftName
          }
        }
      },
      storeChange(v){
        for(let item of this.stores){
          if(item.id==v){
            this.admin.storeName = item.name
          }
        }
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.admin.roleIds = this.roleIds;
              if (this.isEdit) {
                updateAdmin(this.$route.query.id, this.admin).then(response => {
                  if(response.code==200){
                  this.$refs[formName].resetFields();
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration:1000
                  });
                  this.$router.back();
                  }else{
                  this.$message({
                    message: response.msg,
                    type: 'error',
                    duration:1000
                  });

                }


                });
              } else {
                createAdmin(this.admin).then(response => {
                  if(response.code==200)
                {
                  this.$refs[formName].resetFields();
                  this.admin = Object.assign({}, defaultAdmin);
                  this.$message({
                    message: '提交成功',
                    type: 'success',
                    duration: 1000
                  });
                }else{
                  this.$message({
                    message: response.msg,
                    type: 'error',
                    duration:1000
                  });

                }
                });
              }
            });

          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.admin = Object.assign({},defaultAdmin);
      }
    }
  }
</script>
<style>
</style>


